import { useEffect, useState } from 'react';
import styles from './configrule.less';
import { PageContainer } from '@ant-design/pro-layout'
import { history } from 'umi'
import { TreeSelect, Card, Button, message } from 'antd';
import { get_role, rule_list, set_role_scopes } from '@/services/admin/role/role';

const { SHOW_CHILD } = TreeSelect;

export default function Page() {
  const [sysrule, setsysrule] = useState([])
  const [choose, setchoose] = useState([])
  const [onrole, setonrole] = useState(0)
  const get_sysrule = async (role_id: number) => {
    // 获取当前角色已经分配到权限
    const role = await get_role({ role_id })
    if (role.code === 200) {
      setchoose(role.data)
    } else {
      message.info(role.message)
    }
    setonrole(role_id)
    window.console.log(role)
    // 获取系统角色
    const res = await rule_list()
    if (res.code === 200) {
      setsysrule(res.data)
    } else {
      message.info(res.message)
    }
  }
  useEffect(() => {
    if (!history.location.query?.role) {
      history.goBack()
    }
    get_sysrule(Number(history.location.query?.role))
    return () => {
    }
  }, [])

  const ruleChange = (rule: any) => {
    window.console.log(rule)
    setchoose(rule)
  }

  const setScopes = async () => {
    const res = await set_role_scopes({ role_id: onrole, scopes: choose })
    if (res.code === 200) {
      message.success(res.message)
    } else {
      message.info(res.message)
    }
  }

  return (
    <PageContainer
      // header={{title:"权限分配"}}
      title={`正在设置 ${history.location.query?.role_name} 角色的权限`}
      footer={[
      <Button key="goback" onClick={()=>history.goBack()} type="ghost">返回角色管理</Button>,
      <Button key="setrule" onClick={setScopes} type="primary">更新权限</Button>,
    ]}
    >
      <Card style={styles.card} bodyStyle={{ minHeight: 700 }}>
        <TreeSelect
          treeData={sysrule}
          size="large"
          defaultOpen={true}
          value={choose}
          style={{ width: "100%" }}
          onChange={ruleChange}
          treeCheckable={true}
          placeholder="请选择权限"
          listHeight={500}
          showCheckedStrategy={SHOW_CHILD}
          treeDefaultExpandAll={true}
        />
      </Card>
    </PageContainer>
  );
}
